﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

using System.Net;
using System.Xml.Serialization;
using System.Xml.Linq;
using System.IO;
using System.Data;
using System.Collections;
using System.Runtime.Serialization.Json;
using System.Text;

public partial class Default3 : System.Web.UI.Page
{
    string jscript = string.Empty;
    string Deliverscript = string.Empty;
    string DeliverscriptOnIndexChange = string.Empty;
    string jscriptOnIndexChange = string.Empty;
    ArrayList RefershRate = new ArrayList();
    ArrayList Time = new ArrayList();
    protected void Page_Load(object sender, EventArgs e)
    {
        if (Request.Cookies["CookieUserID"] == null)
        {
            Response.Redirect("Login.aspx");
        }

        else
        {


            if (!IsPostBack)
            {
                //  lblLocaltime.Text = DateTime.Now.AddHours(-5).ToShortDateString() + " 09:00:00" + ddlAmPm.SelectedItem.Text;
                lblLocaltime.Text = DateTime.Now.AddHours(-5).ToShortDateString() + "  " + ConvertToUnixTimestamp(DateTime.Now.AddHours(-5).ToShortDateString() + " 09:00:00" + ddlAmPm.SelectedItem.Text);
                GetAQllZohoDeliverers(ConvertToUnixTimestamp(DateTime.Now.AddHours(-5).ToShortDateString() + " 09:00:00" + ddlAmPm.SelectedItem.Text), "500");
                for (int i = 0; i < gvMain.Rows.Count; i++)
                {
                    CheckBox chkDeliverer = (CheckBox)(gvMain.Rows[i].FindControl("chkDeliverer"));
                    chkDeliverer.Checked = true;
                }
                BindDropDowns();

            }
        }
        if (Request.Cookies["CookieUserID"] != null)
        {
            HttpCookie CookieID;
            CookieID = Request.Cookies["CookieUserID"];
            
            //divChangePassword.Visible = true;
            
        }
    }
    public void GetAQllZohoDeliverers(string MonitorStartTime, string NumerOfInstaPlots)
    {
        HttpWebRequest request = WebRequest.Create("https://creator.zoho.com/api/json/king-telemarketing-system/view/InfoDeliverers?authtoken=aad0610e3363259d479310ddb9363b9c&scope=creatorapi&zc_ownername=avanci01&raw=true") as HttpWebRequest;
        request.Method = "GET";

        HttpWebResponse response = request.GetResponse() as HttpWebResponse;
        if (response.StatusCode == HttpStatusCode.OK)
        {
            Stream responseStream = response.GetResponseStream();
            StreamReader reader = new StreamReader(responseStream);
            string str = reader.ReadToEnd();

            System.Web.Script.Serialization.JavaScriptSerializer oSerializer = new System.Web.Script.Serialization.JavaScriptSerializer();
            DeliverersCollection Alldeliverers = (DeliverersCollection)(oSerializer.Deserialize(str, typeof(DeliverersCollection)));
            DataTable dtdeliver = new DataTable();
            dtdeliver.Columns.Add(new DataColumn("Deliverer"));
            dtdeliver.Columns.Add(new DataColumn("InstamapperAPIkey"));
            dtdeliver.Columns.Add(new DataColumn("Zoho_Authtoken"));
            dtdeliver.Columns.Add(new DataColumn("PathColor"));

            foreach (Deliverers DeliverName in Alldeliverers.EJECUTIVOS)
            {
                DataRow row = dtdeliver.NewRow();
                row["Deliverer"] = DeliverName.Empleado;
                row["InstamapperAPIkey"] = DeliverName.InstamapperAPIkey;
                row["Zoho_Authtoken"] = DeliverName.Zoho_Authtoken;
                row["PathColor"] = DeliverName.PathColor;
                dtdeliver.Rows.Add(row);
            }

            gvMain.DataSource = dtdeliver;
            gvMain.DataBind();
          string  JsScript = string.Empty;
            for (int delvrIndx = 0; delvrIndx < Alldeliverers.EJECUTIVOS.Count; delvrIndx++)
            {
                //if (delvrIndx == 2)
               // {
                    try
                    {
                        JsScript = PlaceZohoCustomersAndInstaMaper(Alldeliverers.EJECUTIVOS[delvrIndx].Zoho_Authtoken, Alldeliverers.EJECUTIVOS[delvrIndx].InstamapperAPIkey, delvrIndx.ToString(), Alldeliverers.EJECUTIVOS[delvrIndx].PathColor, MonitorStartTime, NumerOfInstaPlots, Alldeliverers.EJECUTIVOS[delvrIndx].Empleado);
                    }
                    catch (Exception)
                    {
                        continue;
                    }
                //}

            }

            js.Text = "<script type=\"text/javascript\"> var markersArray= []; var markerIndex=-1; $(document).ready(function () { var obj; var infowindow = new google.maps.InfoWindow();  " + JsScript + " });   </script>";
               
        }
    }

    public string PlaceZohoCustomersAndInstaMaper(string Zoho_Authtoken, string InstamapperAPIkey, string keyIndexForChange, string PathColor, string MonitorStartTime, string NumerOfInstaPlots, string DelivererName)
    {
        HttpWebRequest requestCustomers = WebRequest.Create("https://creator.zoho.com/api/json/king-telemarketing-system/view/Acciones_del_dia?authtoken=" + Zoho_Authtoken + "&scope=creatorapi&zc_ownername=avanci01&raw=true") as HttpWebRequest;
        requestCustomers.Method = "GET";
        HttpWebResponse responseCustomers;
        responseCustomers = requestCustomers.GetResponse() as HttpWebResponse;
        if (responseCustomers.StatusCode == HttpStatusCode.OK)
        {
           
            Stream responseCustomerStream = responseCustomers.GetResponseStream();
            StreamReader readerCustomer = new StreamReader(responseCustomerStream);
            string strCusotmer = readerCustomer.ReadToEnd();

            jscript += "var i; obj = " + strCusotmer + @";
            $.each(obj.ACCIONES, function () {

                 var latLng = new google.maps.LatLng(this['Latitud'],this['Longitud']);
                 var Lat=this['Latitud']; var Long=this['Longitud']; var Nombre_Moral_Fisica=this['Nombre_Moral_Fisica'];
                 var Numero_de_Cliente=this['Numero_de_Cliente'];var Numero_SAE=this['Numero_SAE'];
                 var Ejecutivo=this['Ejecutivo'] ; var Accion_a_Realizar =this['Accion_a_Realizar'];
                 var Comentarios=this['Comentarios']; var Colonia=this['Colonia'];
                 var OK=this['OK'];
var image='';
                if (OK == 'OK') {
            image = 'images/green.png';
        }
        else {
            image = 'images/" + PathColor + @".png';
        }

                 var marker = new google.maps.Marker
                              ({  

                              position: latLng,  
                              map: map,icon: image,  
                              draggable: false

                              });
                     google.maps.event.addListener(marker, 'click', (function (marker, i) 
                            { 
                            
                               return function () 
                                  {  
                                     infowindow.setContent('<div>Nombre_Moral_Fisica:'+Nombre_Moral_Fisica+'<br>Numero_de_Cliente:'+Numero_de_Cliente+' <br> Numero_SAE:'+Numero_SAE+'<br>Ejecutivo:'+Ejecutivo+'<br/><br/>Accion_a_Realizar:'+Accion_a_Realizar+' <br/><br/>Comentarios:'+Comentarios+'  <br/><br/>Colonia:'+Colonia+' <br>N:'+Lat+' <br>W:'+Long+'</div>');
                                     infowindow.open(map, marker);
                                  }
                             }) (marker, i)); 
                });";

            return jscript = jscript + CreateInstaMapperPlot(InstamapperAPIkey, NumerOfInstaPlots, MonitorStartTime, keyIndexForChange, PathColor, DelivererName);
        }
        else {
            return "";
        }
       
    }




    public String CreateInstaMapperPlot(string InstamapperAPIkey, string NumerOfInstaPlots, string MonitorStartTime, string keyIndexForChange, string PathColor, string DelivererName)
    {
        string jscriptInstaMaper = string.Empty;
        string strWebURL = "http://www.instamapper.com/api?action=getPositions&key=" + InstamapperAPIkey + "&num=" + NumerOfInstaPlots + "&format=json";
        if (MonitorStartTime != "0")
            strWebURL += "&from_ts=" + MonitorStartTime;
        HttpWebRequest requestCustomers = WebRequest.Create(strWebURL) as HttpWebRequest;
        requestCustomers.Method = "GET";
        HttpWebResponse responseCustomers = requestCustomers.GetResponse() as HttpWebResponse;
        if (responseCustomers.StatusCode == HttpStatusCode.OK)
        {
            Stream responseCustomerStream = responseCustomers.GetResponseStream();
            StreamReader readerCustomer = new StreamReader(responseCustomerStream);
            string strDeliverersPosition = readerCustomer.ReadToEnd();
            System.Web.Script.Serialization.JavaScriptSerializer oSerializerDeliverersPosition = new System.Web.Script.Serialization.JavaScriptSerializer();
            DeliverersPositionCollection AllDeliverersPosition = (DeliverersPositionCollection)(oSerializerDeliverersPosition.Deserialize(strDeliverersPosition, typeof(DeliverersPositionCollection)));
            DataTable dt = new DataTable();
            dt.Columns.Add(new DataColumn("Latitude"));
            dt.Columns.Add(new DataColumn("Longitude"));
            dt.Columns.Add(new DataColumn("device_key"));
            dt.Columns.Add(new DataColumn("heading"));
            dt.Columns.Add(new DataColumn("speed"));
            dt.Columns.Add(new DataColumn("timestamp"));
            foreach (DelivererPosition DeliverersPosition in AllDeliverersPosition.positions)
            {
                if (DeliverersPosition.latitude != "" && DeliverersPosition.longitude != "")
                {
                    DataRow row = dt.NewRow();
                    row["Latitude"] = DeliverersPosition.latitude;
                    row["Longitude"] = DeliverersPosition.longitude;
                    row["device_key"] = DeliverersPosition.device_key;
                    row["heading"] = DeliverersPosition.heading;
                    row["speed"] = DeliverersPosition.speed;
                    row["timestamp"] = DeliverersPosition.timestamp;
                    dt.Rows.Add(row);
                }
            }
            if (dt.Rows.Count > 0)
            {
                jscriptInstaMaper += GPSLib.AddInstamaperPlots(dt, keyIndexForChange, PathColor, true, chkIsNameVisible.Checked, DelivererName);
                GPSLib.AddInstamaperPlotsTable(dt, litTablHTML, keyIndexForChange);
            }
            
        }

        return jscriptInstaMaper;

    }


    public static string ConvertToUnixTimestamp(string date)
    {
        // date =  TimeZoneInfo.ConvertTimeBySystemTimeZoneId(date, TimeZoneInfo.Local.Id, ddlTimeZone.SelectedValue).ToString();

        DateTime origin = new DateTime(1970, 1, 1, 0, 0, 0, 0);

        TimeSpan diff = Convert.ToDateTime(date).AddHours(-5) - origin;

        //return "1344002400";
        return Convert.ToInt32(Math.Floor(diff.TotalSeconds)).ToString();

    }


    protected void btnSearch_Click(object sender, EventArgs e)
    {
        string JsScript = string.Empty;
        DateTime date = new DateTime();
        date = DateTime.Now;

        string T = DateTime.Now.AddHours(-5).ToShortDateString() + " " + ddlTime.SelectedValue + ":00:00" + ddlAmPm.SelectedItem.Text;
        lblLocaltime.Text = DateTime.Now.AddHours(-5).ToString() + "  " + ConvertToUnixTimestamp(T);
        for (int i = 0; i <= gvMain.Rows.Count; i++)
        {
            try
            {
                if (((CheckBox)gvMain.Rows[i].FindControl("chkDeliverer")).Checked)
                    JsScript += PlaceZohoCustomersAndInstaMaper(((Label)gvMain.Rows[i].FindControl("lblAuthToken")).Text, ((Label)gvMain.Rows[i].FindControl("lblInstamapperAPIkey")).Text, i.ToString(), ((Label)gvMain.Rows[i].FindControl("lblPathColor")).Text, ConvertToUnixTimestamp(T), txtNumber.Text, ((CheckBox)gvMain.Rows[i].FindControl("chkDeliverer")).Text);
            }
            catch (Exception)
            {
                continue;
            }
        }
        js.Text = "<script type=\"text/javascript\"> var markersArray= []; var markerIndex=-1; $(document).ready(function () { var obj; var infowindow = new google.maps.InfoWindow();  " + JsScript + " });   </script>";
        if (ddlRefershRate.SelectedValue != "0")
        {
            LtrlPathFollowed.Text = "<script type=\"text/javascript\">	var timer;  function ReloadPage() {$(\"#btnSearch\").click();};$(document).ready(function () {timer = setTimeout(\"ReloadPage()\"," + Convert.ToInt32(ddlRefershRate.SelectedValue) * 60 * 1000 + ");});</script>";
            LtrlPathFollowed.Text += "<script type=\"text/javascript\">function stoptimer() {clearTimeout(timer);}</script>";
        }
    }
    public void BindDropDowns()
    {

        for (int i = 0; i <= 20; i = i + 2)
        {
            RefershRate.Add(i);
        }
        ddlRefershRate.DataSource = RefershRate;
        ddlRefershRate.DataBind();
        for (int Tim = 1; Tim <= 12; Tim++)
        {
          ddlTime.Items.Add(new ListItem(Tim.ToString()));
        }
        ddlTime.SelectedValue = "9";
    }

    protected void lnkLogOut_Click(object sender, EventArgs e)
    {

        HttpCookie CookieUserID = new HttpCookie("CookieUserID");
        CookieUserID.Expires = DateTime.Now.AddDays(-30);

        Response.Cookies.Add(CookieUserID);

        Response.Redirect("Login.aspx");
    }
}
